------------------------------------------------------------------------------------------------------------------------------------------------
-- -- tasks base lib
local function language_change_say(theNPC)
    theNPC.CHAT_TABLE = {}
    pcall(function()
        -- theNPC.npc_base_lib:Get_Language() == "ch"
        theNPC.CHAT_TABLE = TUNING.NPC_CHAT_TABLE[ theNPC.npc_base_lib:Get_Language() ] ["npc_event_butterflies"] or {}
    end)
end

-------------------------------------------------------------------------------------------------------------------------------------------------
local function BUTTERFLY_TASK_INIT(inst)
    local butterfly = inst.entity:GetParent()
    ---- 给蝴蝶添加被抓捕时候的处理  onpickup event 的添加和移除
    butterfly.___onpickup_fn = function(butterfly)
        pcall(function()
            ------ 移除debuff
            local debuff_inst = butterfly:GetDebuff("npc_event_butterflies")
            if debuff_inst then
                debuff_inst:Remove()
            end
            ------ 移除 onpickup event
            if butterfly.___onpickup_fn then
                butterfly:RemoveEventCallback("onpickup",butterfly.___onpickup_fn)
                butterfly.___onpickup_fn = nil
            end
            ----- 移除超时任务
            if butterfly.__time_out_task then
                butterfly.__time_out_task:Cancel()
                butterfly.__time_out_task = nil
            end
            ------ 重启脑子
            butterfly:SetBrain(require "brains/butterflybrain")
            butterfly:RestartBrain()
            ---- 从NPC的列表里删除
            butterfly.__tarNPC.__butterflies_list[butterfly] = function() return false end
        end)        
    end

    butterfly:ListenForEvent("onpickup",butterfly.___onpickup_fn)

    butterfly.__time_out_task = butterfly:DoTaskInTime(200,function()
        local x,y,z = butterfly.Transform:GetWorldPosition()
        butterfly:Remove()
        SpawnPrefab("flower_rose").Transform:SetPosition(x,0,z)
    end)

end

local function BUTTERFLY_TASK(inst)
    local butterfly = inst.entity:GetParent()
    local theplayer = butterfly.__tarplayer
    if theplayer == nil or not theplayer:IsValid() then
        butterfly:Remove()
        return
    end
    local distance = butterfly.npc_base_lib:Distance_Targets(butterfly,butterfly)
    if distance > 7 then
        butterfly.components.locomotor.runspeed  = 25
        butterfly.components.locomotor.walkspeed  = 25
    else
        butterfly.components.locomotor.runspeed = 6
        butterfly.components.locomotor.walkspeed = 6
    end
    if butterfly.event_step == nil then
        butterfly.npc_base_lib:Run_Around_Target_In_Range({target = theplayer,range = 8,random_range_flag = true , mid_reflash_range = 2})
    end

end

--------------------------------------------------------------------------------------------------------------------------------------------------

local function Time_Out_Leave(inst)
    local theNPC = inst.entity:GetParent()
    local time = theNPC.npc_base_lib:Get_Time_Out()
    if time then
        inst:DoTaskInTime(time,function()
            inst:Remove()
            theNPC:AddDebuff("npc_event_leave","npc_event_leave")
            theNPC.npc_base_lib:Say(theNPC.CHAT_TABLE.time_out)
            print("Warning : npc time out and leave")
        end)
    end
end
-------------------------------------------------------------------------------
local function UseBugnet(theNPC)
    theNPC.npc_base_lib:Action_Bugnet(nil,true)
end
local function give_bug_net(theNPC,theplayer)
    local whip = SpawnPrefab("bugnet")
    theNPC.npc_base_lib:Change_Item_Skin(whip)
    theplayer.components.inventory:GiveItem(whip)
end
local function butterfiles_check(theNPC)   -- 还有蝴蝶retrun false，  蝴蝶没了 retrun true
    for butterfly, fn in pairs(theNPC.__butterflies_list) do
        if butterfly and fn() then
            return false
        end
    end
    return true
end

local function Create_Butterflies(theNPC)
    local theplayer = theNPC:GetPlayer()
    local points = theNPC.npc_base_lib:GetSurroundPoints({target = theplayer,range = 25,num = 40})
    theNPC.__butterflies_list = {}
    for i, pt in pairs(points) do
        theNPC:DoTaskInTime(0.2*(i-1),function() --- 用一下延迟，0.2秒刷一只，避免瞬间大量造成的游戏卡顿
            local butterfly = SpawnPrefab("butterfly")
            butterfly:SetBrain(nil)
            butterfly.Transform:SetPosition(pt.x,0,pt.z)
            theNPC.__butterflies_list[butterfly] = function() return butterfly:IsValid()  end
            butterfly:AddComponent("npc_base_lib")
            butterfly:AddComponent("npc_everything_data")
            butterfly.__tarplayer = theplayer
            butterfly.__tarNPC = theNPC
            butterfly:AddDebuff("npc_event_butterflies","npc_event_butterflies")    
        end)            
    end
end
-------------------------------------------------------------------------------
local function NPC_TASKS_INIT(inst)
    local theNPC = inst.entity:GetParent()
    language_change_say(theNPC)
    Time_Out_Leave(inst)
    
    theNPC.npc_base_lib:Equip_Random_Hat()
    theNPC.npc_base_lib:Equip_Random_Cloth()
    -- theNPC.npc_base_lib:Equip_Random_Weapon()
    theNPC:AddTag("INLIMBO")
    theNPC:AddTag("notarget")
    theNPC:AddTag("noattack")
    theNPC:AddTag("invisible")
    -- theNPC:AddTag("Unable_To_Refuse")
    theNPC.npc_event = inst.prefab

    local whip = SpawnPrefab("bugnet")
    theNPC.npc_base_lib:Change_Item_Skin(whip)
    theNPC.npc_base_lib:Equip(whip)
    Create_Butterflies(theNPC)
end

local function NPC_TASKS(inst)
    local theNPC = inst.entity:GetParent()
    if TheWorld.state.isnight  or TheWorld:HasTag("cave") then
        theNPC.npc_base_lib:Try_2_Set_Light(true)
    else
        theNPC.npc_base_lib:Try_2_Set_Light(false)
    end
    local theplayer = theNPC.__link_player
    if theplayer == nil or theplayer:IsValid() == false then
        -- theNPC:RemoveDebuff(inst.prefab)
        inst:Remove()
        theNPC:AddDebuff("npc_event_leave","npc_event_leave")
        print("Warning : theNPC.__link_player == nil")
        return
    end

    if theNPC.event_step == nil then
        if theNPC.npc_base_lib:Close_2_Target_In_Range({range = 4.5}) == true then
            theNPC.event_step = 1
        end        
    elseif theNPC.event_step == 1 then
        local wait_time = theNPC.npc_everything_data:Add("wait.000",1)
        if wait_time%3 == 0 then
            theNPC.event_step = 2
        end
        if wait_time == 1 then
            theNPC.npc_base_lib:Say(theNPC.CHAT_TABLE.bugnet)
            give_bug_net(theNPC,theplayer)
        end
    elseif theNPC.event_step == 2 then
        if butterfiles_check(theNPC) == false then
            theNPC.npc_base_lib:Run_Around_Target_In_Range({range = 4,random_range_flag = true , mid_reflash_range = 1,fn = UseBugnet})
        else
            theNPC.event_step =3
        end
    elseif theNPC.event_step == 3 then
        -- theNPC.event_step = theNPC.event_step + 1
        -- theNPC:RemoveDebuff(inst.prefab)
        theNPC.npc_base_lib:Say("Bye ~")
        inst:Remove()
        theNPC:AddDebuff("npc_event_leave","npc_event_leave")
    end
end
--------------------------------------------------------------------------------------------------------------------------------------------------

local function OnAttached(inst,target) -- when the debuff on or player is newSpawn(or through the cave)
    inst.entity:SetParent(target.entity)
    inst.Network:SetClassifiedTarget(target)
    local BUTTERFLY_OR_NPC = inst.entity:GetParent()

    local flag ,error_code= pcall(function(inst,target)
        if TheWorld.ismastersim then

            if BUTTERFLY_OR_NPC:HasTag("npc") then
                NPC_TASKS_INIT(inst)
            else
                BUTTERFLY_TASK_INIT(inst)
            end

        end
    end,inst,target)
    if flag == false  then
        print("Error : OnAttached(inst,target) ",inst.prefab)
        print(error_code)
        BUTTERFLY_OR_NPC:Remove()
    end
end

local function OnDetached(inst) -- When eliminating from the outside
    local player = inst.entity:GetParent()   
    -- print(" FROM OUSIDE REMOVE ")
    
    -- inst:Remove()
end

local function ExtendDebuff(inst)
    -- inst.countdown = 3 + (inst._level:value() < CONTROL_LEVEL and EXTEND_TICKS or math.floor(TUNING.STALKER_MINDCONTROL_DURATION / FRAMES + .5))
end



local function OnUpdate(inst,ismastersim)
    local BUTTERFLY_OR_NPC = inst.entity:GetParent()

    local flag,error_code = pcall(function(inst,ismastersim)
        -- local NPC = inst.entity:GetParent()
        if TheWorld.ismastersim then
            if BUTTERFLY_OR_NPC:HasTag("npc") then
                NPC_TASKS(inst)
            else
                BUTTERFLY_TASK(inst)
            end

        end
    end,inst,ismastersim)
    if flag == false then
        print("Error : OnUpdate(inst,ismastersim) ,step:",BUTTERFLY_OR_NPC.event_step ,inst.prefab)
        print(error_code)
        BUTTERFLY_OR_NPC:Remove()
    end
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddNetwork()

    inst:AddTag("CLASSIFIED")


    -- inst:DoPeriodicTask(1, OnUpdate, nil, TheWorld.ismastersim)  -- in one seconds
    inst:DoPeriodicTask( 0.5, OnUpdate, nil, TheWorld.ismastersim)  -- in 0.5 seconds

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("debuff")
    inst.components.debuff:SetAttachedFn(OnAttached)
    inst.components.debuff.keepondespawn = true -- 是否保持debuff 到下次登陆
    -- inst.components.debuff:SetDetachedFn(inst.Remove)
    inst.components.debuff:SetDetachedFn(OnDetached)
    -- inst.components.debuff:SetExtendedFn(ExtendDebuff)
    -- ExtendDebuff(inst)


    return inst
end

return Prefab("npc_event_butterflies", fn)
